Reverse a LinkedList (easy)

Problem Statement #

Given the head of a Singly LinkedList, reverse the LinkedList. Write a function to return the new head of the reversed LinkedList.

Created with Fabric.js 1.6.0-rc.1 2 4 6 8 10 null Original List: Reversed List: Example: 2 4 6 8 10 null head head

Try it yourself #

Try solving this question here:

Output

0.464s

Nodes of original LinkedList are: 2 4 6 8 10 Nodes of reversed LinkedList are: 2 4 6 8 10

Solution #

To reverse a LinkedList, we need to reverse one node at a time. We will start with a variable current which will initially point to the head of the LinkedList and a variable previous which will point to the previous node that we have processed; initially previous will point to null.

In a stepwise manner, we will reverse the current node by pointing it to the previous before moving on to the next node. Also, we will update the previous to always point to the previous node that we have processed. Here is the visual representation of our algorithm:

Created with Fabric.js 1.6.0-rc.1 current 2 4 6 8 10 null previous = null current = head, previous = null
1 of 7
Created with Fabric.js 1.6.0-rc.1 current 4 6 8 10 null previous 2 null
2 of 7
Created with Fabric.js 1.6.0-rc.1 current 6 8 10 null previous 2 null 4
3 of 7
Created with Fabric.js 1.6.0-rc.1 current 8 10 null previous 2 null 4 6
4 of 7
Created with Fabric.js 1.6.0-rc.1 current 10 null previous 2 null 4 6 8
5 of 7
Created with Fabric.js 1.6.0-rc.1 current null previous 2 null 4 6 8 10
6 of 7
Created with Fabric.js 1.6.0-rc.1 2 null 4 6 8 10 head
7 of 7

Code #

Here is what our algorithm will look like:

Output

0.463s

Nodes of original LinkedList are: 2 4 6 8 10 Nodes of reversed LinkedList are: 10 8 6 4 2

Time complexity #

The time complexity of our algorithm will be O(N)O(N) where ā€˜N’ is the total number of nodes in the LinkedList.

Space complexity #

We only used constant space, therefore, the space complexity of our algorithm is O(1)O(1).

Mark as Completed
←    Back
Introduction
Next    →
Reverse a Sub-list (medium)